<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /**
         * 
         * 回文字串
         * 输入："abc"
         * 输出：3 
         * 解释：三个回文子串: "a", "b", "c"
         * 
         * 输入："aaa"
         * 输出：6
         * 解释：6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
         * 
        */
        /* 
            时间：O(n * m)
            空间：O(1)
        */
        // 中心展开
        var countSubstrings = function(s) {
            // 依次遍历abc的每个字符，每个字符为基准点向两边扩展，是否是相等，相等就++
            // 基准点可能是一个字符，也可能是两个字符
            let result = 0;
            for (let i = 0; i < s.length; i++) {
                result += extend(s, i, i, s.length)
                result += extend(s, i, i + 1, s.length)
            }
            return result
        };
        const extend = (s, i, j, n) => {
            let res = 0
            while (i >= 0 && j < n && s[i] === s[j]) {
                i--
                j++
                res++
            }
            return res
        }
        console.log(countSubstrings('abc'));
        console.log(countSubstrings('aaa'));
    </script>
</body>

</html>